package users

import (
	"sieve_admin_server_userpass/pkg/cache"
	"sieve_admin_server_userpass/pkg/im3/db"
	"sieve_admin_server_userpass/pkg/log"
)

var (
	c    = cache.PeriodLoad(db.LoaderPeriod, loadData)
	dbok = false
)

func init() {
	db.OnConnected(func() {
		dbok = true
		c.Load()
	})
}

type cacheData struct {
	all         []*User
	m           map[int]*User
	activated   []*User
	unactivated []*User
	deactivated []*User
}

type User struct {
	Uid          int
	Name         string
	Avatar       string
	Phone        string
	Email        string
	Pwd          string
	PubKey       string
	Dept         int
	Company      int
	ContactLevel int
	UpdateTime   int64
}

func loadData() (data *cacheData) {
	data = &cacheData{
		all:         []*User{},
		m:           map[int]*User{},
		activated:   []*User{},
		unactivated: []*User{},
		deactivated: []*User{},
	}
	if !dbok {
		return
	}
	rows, err := db.Mysql().Query("SELECT `Uid`,`Name`,`Avatar`,`Phone`,`Email`,`Pwd`,`PubKey`,`Dept`,`Company`,`ContactLevel`,`UpdateTime` FROM `User` ORDER BY `Uid`")
	if err != nil {
		log.Err(err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		u := &User{}
		if err := rows.Scan(
			&u.Uid,
			&u.Name,
			&u.Avatar,
			&u.Phone,
			&u.Email,
			&u.Pwd,
			&u.PubKey,
			&u.Dept,
			&u.Company,
			&u.ContactLevel,
			&u.UpdateTime,
		); err != nil {
			log.Err(err)
			return
		}
		data.all = append(data.all, u)
		data.m[u.Uid] = u
		if u.Pwd != "" && u.PubKey != "" {
			data.activated = append(data.activated, u)
		} else if u.Pwd != "" {
			data.unactivated = append(data.unactivated, u)
		} else {
			data.deactivated = append(data.deactivated, u)
		}
	}
	return
}

func Reload() {
	c.Load()
}

func GetAll() []*User {
	return c.Get().all
}

func Get(uid int) *User {
	return c.Get().m[uid]
}

func GetActivated() (activated, unactivated, deactivated []*User) {
	u := c.Get()
	return u.activated, u.unactivated, u.deactivated
}
